package com.wbao.dianniu.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.AmDataChangeManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.manager.ShareSDKManager;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

/**
 * 匿名八卦
 * 
 * @author yejianjun
 *
 */
public class AnonymousAdapter extends BaseAdapter implements IQuestDelListener {
	private Context mContext;
	List<QaResponse> mList;
	private LayoutInflater mInflater;
	int maxDescripLine = 3;
	private int type;
	private final int TYPE_ANONYMOUS = 1;
	private final int TYPE_PARININ = 2;
	private QuestDelManager manager;
	private int position;
	
	public AnonymousAdapter(Context ctx,int type) {
		mContext = ctx;
		mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mList = new ArrayList<QaResponse>();
		this.type = type;
		if(TYPE_ANONYMOUS == type){
			manager = new QuestDelManager(mContext);
			manager.addQuestDelListener(this);
		}else if(TYPE_PARININ == type){
			
		}
		
	}
	
	/**
	 * 清空数据
	 * @param list
	 */
	public void cleanData(){
		if(null != mList){
			mList.clear();
		}
		
	}
	
	public void addDataList(List<QaResponse> list){
		if(null == mList){
			return;
		}
		for (int i = 0; i < list.size(); i++) {
			mList.add(list.get(i));
		}
	}
	
	public void setData(List<QaResponse> list){
		if(null == mList){
			mList = new ArrayList<QaResponse>();
		}
		mList = list;
	}
	
	public List<QaResponse> getList() {
		return mList;
	}
	
	@Override
	public int getCount() {
		if (null == mList)
			return 0;
		else
			return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		GridHolder holder =null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.anonymous_list_item, null);   
			holder = new GridHolder();
			holder.forwardTV = (TextView) convertView.findViewById(R.id.anonymous_forward_counts);
			holder.praiseTV = (TextView) convertView.findViewById(R.id.anonymous_praise_tv);
			holder.praiseIV = (ImageView) convertView.findViewById(R.id.anonymous_praise_iv);
			holder.commentTV = (TextView) convertView.findViewById(R.id.anonymous_comment_tv);
			holder.shareLayout = (LinearLayout) convertView.findViewById(R.id.shareLayout_anonymous);
			holder.praiseLayout = (LinearLayout) convertView.findViewById(R.id.praiseLayout_anonymous);
			holder.responseLayout = (LinearLayout) convertView.findViewById(R.id.responseLayout_anonymous);
			holder.gridview = (CanDoBlankGridView) convertView.findViewById(R.id.anony_gridview);
			holder.content  = (TextView) convertView.findViewById(R.id.anonymous_content);
			holder.deleteBtn = (Button) convertView.findViewById(R.id.anonymous_list_delete);
			convertView.setTag(holder); 
		}else{
			 holder = (GridHolder) convertView.getTag();   
		}
		if(null == mList || mList.size() < position){
			return convertView;
		}
		if(type == TYPE_ANONYMOUS){
			holder.deleteBtn.setVisibility(View.VISIBLE);
		}else if(type == TYPE_PARININ){
			holder.deleteBtn.setVisibility(View.GONE);
		}
		
		final QaResponse resp = mList.get(position);
		if(null != resp){
			holder.content.setText(resp.content);
			//是否点赞
			if(0 == resp.isGood){
				holder.praiseIV.setImageResource(R.drawable.click_praise_icon_nor);
			}else{
				holder.praiseIV.setImageResource(R.drawable.click_praise_icon_sel);
			}
			holder.forwardTV.setText(resp.forwardCount + "");
			Utils.showPriseCounts(resp.goodCount, holder.praiseTV);
			Utils.showPriseCounts(resp.answerCount, holder.commentTV);
		}
		holder.deleteBtn.setOnClickListener(new DeleteListener(position,resp.id));
		holder.content.setOnClickListener(new DetailListener(resp,position));
		holder.praiseLayout.setOnClickListener(new praiseListener(position,resp.isGood,resp.goodCount));
		//分享
		holder.shareLayout.setOnClickListener(new ShareListener(resp));
		holder.responseLayout.setOnClickListener(new DetailListener(resp,position));
		if(TextUtils.isEmpty(resp.questImgs)){
			  holder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
      } else {
      	ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
      	holder.gridview.setVisibility(View.VISIBLE);
      	//通过图片张数 设置gridview的高度 
      	double multiple = Math.ceil((float)imageUrls.size()/GlobalContext.NUMCOLUMNS);
    	int height = (int) (Utils.dip2px(mContext, 80) * multiple + (multiple -1) * Utils.dip2px(mContext, 10));
    	int width = 0;
    	if(multiple >= 1){
    		width = Utils.dip2px(mContext, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS -1) * Utils.dip2px(mContext, 5);
    	}else{
    		width = Utils.dip2px(mContext, 80) * imageUrls.size() + (imageUrls.size()  -1) * Utils.dip2px(mContext, 5);
    	}
    	width = width + Utils.dip2px(mContext, 10);// 加上pendingLeft 10dp
    	LinearLayout.LayoutParams lp = new LayoutParams(width, height);
    	holder.gridview.setLayoutParams(lp);
        holder.gridview.setAdapter(new NoScrollGridAdapter(mContext, imageUrls));
	    // 点击回帖九宫格，查看大图
	    holder.gridview.setOnItemClickListener(new MyItemClickListener(imageUrls));
	    holder.gridview.setOnTouchInvalidPositionListener(new CanDoBlankGridView.OnTouchInvalidPositionListener() {

            @Override
            public boolean onTouchInvalidPosition(int motionEvent) {
				/*
				 * 当返回false的时候代表交由父级控件处理，当return
				 * true的时候表示你已经处理了该事件并不让该事件再往上传递
				 * 。为了出发listview的item点击就得返回false了
				 */
                return false;
            }
        });  
          
      }
		return convertView;
	}
	
	class DeleteListener implements OnClickListener{

		private int index;
		private int questId;
		public DeleteListener(int position,int questId) {
			this.index = position;
			this.questId = questId;
		}
		
		@Override
		public void onClick(View v) {
			//
			CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
			builder.setTitle("确认删除该条匿名吗？");
			builder.setPositiveButton(mContext.getResources().getString(R.string.confirm),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							position = index;
							if (null != manager)
								manager.deleteQuest(GlobalContext.accountId, questId);
						}
					});
			builder.setNegativeButton(mContext.getResources().getString(R.string.cancel),
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();
		}
	} 
	
	/**
	 * 分享
	 */
	private class ShareListener implements OnClickListener{
		private QaResponse resp;
		public ShareListener(QaResponse resp) {
			this.resp = resp;
		}
		@Override
		public void onClick(View v) {
			String imageUrl = null;
			if(TextUtils.isEmpty(resp.questImgs)){
				imageUrl =  GlobalContext.cdndownUrl  + "logo.png";
			}else{
				ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
				imageUrl = imageUrls.get(0);
			}
			ShareSDKManager.getInstance().showShare(mContext,resp.content, 7,imageUrl, resp.id);
		}
		
	}
	
	/**
	 * 点赞
	 */
	class praiseListener implements OnClickListener{

		private int isGood;
		private int position;
		private int goodCount;
		public praiseListener(int position,int isGood,int goodCount) {
			this.isGood = isGood;
			this.position = position;
			this.goodCount = goodCount;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(v.getId() == R.id.praiseLayout_anonymous){
				if(isGood == 0){
					isGood = 1;
					goodCount++;
				}else{
					isGood = 0;
					goodCount--;
				}
				AmDataChangeManager.getInstance().priseNotify(mList.get(position).id, isGood, goodCount);
				goodclick(mList.get(position).id);
			}
		}
	
	}
	private void goodclick(int questId){
		QuestGoodManager manager = new QuestGoodManager(mContext);
		manager.good(GlobalContext.accountId, questId);
	}
	
	/**
	 * 点击查看详情
	 *
	 */
	private class DetailListener implements OnClickListener{
		private QaResponse resp;
		private int pos;
		public DetailListener(QaResponse resp ,int position) {
			this.resp = resp;
			pos = position;
		}
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.anonymous_content:
			case R.id.responseLayout_anonymous:
				Utils.intoAmDetailActivity(mContext, resp);
				break;

			default:
				break;
			}
		}
		
	}
	
	public class GridHolder {
		/** 展开 */
//		public Button openBtn;
		/** 内容 */
		public TextView content;
		
		public TextView forwardTV;
		/** 点赞数 */
		public TextView praiseTV;
		/** 点赞图标 */
		public ImageView praiseIV;
		/** 回复数 */
		public TextView commentTV;
		/** 分享按钮*/
		public LinearLayout shareLayout;
		/** 点赞按钮 */
		public LinearLayout praiseLayout;
		/** 回复按钮 */
		public LinearLayout responseLayout;
		/**	图片显示	*/
		public CanDoBlankGridView  gridview;
		/**	删除按钮	*/
		public Button  deleteBtn;
	}
	
//	@Override
//	public void countsChanged(int questId, int goodCounts, int answerCounts,int isGood) {
//		if (null != mList) {
//			for (int i = 0; i < mList.size(); i++) {
//				if (mList.get(i).id == questId) {
//					mList.get(i).goodCount = goodCounts;
//					mList.get(i).answerCount = answerCounts;
//					mList.get(i).isGood = isGood;
//					notifyDataSetChanged();
//					break;
//				}
//			}
//		}
//	}
	
	public void addOneQuestData(QaResponse addData) {
		if(null != mList){
			mList.add(0, addData);
			notifyDataSetChanged();
		}
	}
	
	class MyItemClickListener implements OnItemClickListener{

		private ArrayList<String> url;
		public MyItemClickListener(ArrayList<String> url) {
			this.url = url;
		}
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			//弹出图片查看按钮
            imageBrower(position, url);
		}
		
	} 
	
	/**
     * 打开图片查看器
     * 
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(mContext, position, urls2);
    }

	public void removeOneData(int id) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == id){
				mList.remove(i);
				notifyDataSetChanged();
				break;
			}
		}
	}

	public void priseNotify(int questId, int isGood, int goodCounts) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.get(i).isGood = isGood;
				mList.get(i).goodCount = goodCounts;
				notifyDataSetChanged();
				break;
			}
		}
	}

	public void replyNotify(int questId, int answerCounts) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.get(i).answerCount = answerCounts;
				notifyDataSetChanged();
				break;
			}
		}
	}

	@Override
	public void onQuestDelFailure(int errorCode, String errorMsg) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onQuestDelSuccess() {
		// TODO Auto-generated method stub
		// 通知其它界面数据改变
		AmDataChangeManager.getInstance().notifyRemove(mList.get(position).id);
	}
    
}
